<?php
class SearchController extends AppController
{
	public $name = "Search";
	public $uses = array('Business', 'Message', 'BusinessDetail', 'Category', 'Offer', 'Field');

	public $paginate = array('Business' =>
	                          array('fields' =>
	                                 array("`Business`.`id`", "`Business`.`name`", "`Business`.`contact_no`",
	                                       "`Business`.`street`", "`Business`.`city`", "`Business`.`state`",
	                                       "`Business`.`zip_code`", "`Business`.`logo`", "`Business`.`plan_id`",
	                                       "`Business`.`website`", "`Business`.`keyword`", "`Business`.`description`",
	                                       "`Business`.`category`", "`User`.`id`", "`User`.`email`", "`Plan`.`name`"),
	                                'limit' => 10
	                                )
 	                         );

	public function index()
	{
		switch ($this->Session->read('projectId')) {
			case 1:
				break;

			case 2:
				self::set('bodywidth', 650);
				self::set('quicksearch', 1);
				self::set('islogin', 0);
				self::render('main');
				break;
		}
	}

	public function main() {}
	public function about()
	{
	        switch ($this->Session->read('projectId')) {
            case 1:
                break;

            case 2:
                self::set('bodywidth', 670);
                self::set('quicksearch', 1);
                self::set('islogin', 0);
                break;
        }
	}

	public function result()
	{
		$conditions = array();
		$_searchfield = null;
		$_extras = null;

		if ($this->data['search']) {
			$searchfield = $this->data['search']['searchfield'];
			$extras = $this->data['search']['extras'];

			// save search fields in session
			$this->Session->write('searchfield', $searchfield);
			$this->Session->write('extras', $extras);

			// create conditional query based on user's input
			if ($searchfield) {
			    if ($this->data['search']['offer']) {

    				$_searchfield = array('OR' =>
    				                       array("`Offer`.`offer_name` LIKE" => "%{$searchfield}%",
    				                             "`Offer`.`ad_network` LIKE" => "%{$searchfield}%",
    				                             "`Offer`.`keywords` LIKE" => "%{$searchfield}%"
    				                             )
    				                      );

        			$_default = array("`Offer`.`active`=1");

        			// generate pagination
        			$paginate = $this->paginate('Offer', array($_default, $_searchfield));

			    } else {
    				$_searchfield = array('OR' =>
    				                       array("`Business`.`name` LIKE" => "%{$searchfield}%",
    				                             "`Business`.`keyword` LIKE" => "%{$searchfield}%"
    				                             )
    				                      );

        			if ($extras) {
        				# parse address to city, state, zip code
        				$address = explode(", ", $extras);
        				$cn = count($address);

        				switch ($cn) {
        					case 1:
        						$_extras = array('OR' =>
        						                  array("`Business`.`city` LIKE '%".$address[0]."%'",
        						                        "`Business`.`state` LIKE '%".$address[0]."%'",
        						                        "`Business`.`zip_code` = '".$address[0]."'"
        						                        )
        						                 );
        						break;

        					case 2:
        						$_extras = array('OR' =>
        						                  array("`Business`.`city` LIKE '%".$address[0]."%'",
        						                        "`Business`.`state` LIKE '%".$address[1]."%'"
        						                        )
        						                 );
        						break;

        					case 3:
        						$_extras = array('OR' =>
        						                  array("`Business`.`city` LIKE '%".$address[0]."%'",
        						                        "`Business`.`state` LIKE '%".$address[1]."%'",
        						                        "`Business`.`zip_code` = '".$address[2]."'"
        						                        )
        						                 );
        						break;
        				}
        			}

        			$_default = array("`Business`.`active`=1",
        			                  "`Business`.`deleted`=0",
        			                  "`Business`.`projectId`=".$this->Session->read('projectId'));


        			// generate pagination
        			$paginate = $this->paginate('Business', array($_default, $_extras, $_searchfield));
                }

			}


		} else {
			$paginate = null;
		}

		// set template values
		switch ($this->Session->read('projectId')) {
			case 2:
				self::set(array('bodywidth' => 446, 'quicksearch' => 0, 'islogin' => 0));
				break;
		}


		self::set(array('results' => $paginate, 'searchfield' => $this->data['search']['searchfield']));
		self::set('offer', $this->data['search']['offer']);
	}

    public function contact()
    {
        # save inquiries information and notify system
        # admininistrator for new inquiries.
		$msg = array('msg_type' => 'CONTACT',
                     'name' => $this->data['contact']['name'],
                     'email' => $this->data['contact']['email'],
                     'body' => $this->data['contact']['body'],
                     'date_created' => date('Y-m-d h:i:s'),
		             'projectId' => $this->Session->read('projectId')
                     );

		$result = $this->Message->_save(0, $msg);
		if ($result) {
			//self::set('alert', 'Thank you for sending your queries. We\'ll get back in touch to you as soon as possible.');
			$msg = 'Thank you for sending your queries. We\'ll get back in touch to you as soon as possible.';
			self::flash($msg, '/search/about/', 5);
		} else {
			self::set('alert', $this->Message->invalidFields());
		}

		self::set('islogin', 0);
        $this->redirect('/search/about');
    }

    public function export_form_fields($offerId)
    {
        $this->layout = "";
        $fields = $this->Field->find('all', array('conditions' => array('offerId' => $offerId)));
        $method = $this->Offer->find('first', array('conditions' => array('id' => $offerId)));

        if ($fields) {
            $output = "<script type='text/javascript' src='http://".$_SERVER['HTTP_HOST']."/lds/js/jquery.js'></script>";
            $output .= "<script type='text/javascript' src='http://".$_SERVER['HTTP_HOST']."/lds/js/jquery_plugins/jquery.metadata.js'></script>";
            $output .= "<script type='text/javascript' src='http://".$_SERVER['HTTP_HOST']."/lds/js/jquery_plugins/jquery.validate.js'></script>";
            $output .= "<script type='text/javascript' src='http://".$_SERVER['HTTP_HOST']."/lds/js/cmxforms.js'></script>";
            $output .= "<link rel='stylesheet' type='text/css' href='http://".$_SERVER['HTTP_HOST']."/lds/css/cmxform.css' />";

            $output .= "<script type='text/javascript'>
                        $().ready(function() {
                            $('#".$fields[0]['Field']['form_name']."').validate({
                                errorLabelContainer: $('#".$fields[0]['Field']['form_name']." div.error')
                            });
                        });
                        </script>";

            $output .= "<style type='text/css'>
                            .".$fields[0]['Field']['form_name']." fieldset p.error label { color: red; }
                            form.".$fields[0]['Field']['form_name']." label.error {
                                display: block;
                                margin-left: 1em;
                                width: auto;
                            }
                            div.error {
                                background-color: #eee;
                                border: 1px solid red;
                                margin: 5px;
                                padding: 5px;
                            }
                        </style>";

            $output .= "<form id='".$fields[0]['Field']['form_name']."' name='".$fields[0]['Field']['form_name']."' action='".$fields[0]['Field']['form_action']."' method='".$method['Offer']['post_method']."' class='".$fields[0]['Field']['form_name']."'>";
            $output .= "<table width='100%'>";
            $output .= "<tr>";
            $output .= "<td colspan='2'><div class='error'></div></td>";
            $output .= "</tr>";

            foreach($fields as $k => $v) {
                $class = "";
                $output .="<tr>";
                $output .= "<td width='20%' align='right'>".$v['Field']['field_label']."&nbsp;&nbsp;</td>";
                $output .= "<td>";

                if ($v['Field']['field_type']) {
                    // add jquery validation
                    if ($v['Field']['validation']) {
                        $pos = stripos($v['Field']['validation'], "length");
                        if ($pos === false) {
                            $class = $v['Field']['validation'].":true";
                        } else {
                            $class = $v['Field']['validation'].":".$v['Field']['validation_param'];
                        }
                    }

                    // check if field is required, if yes, add it to validation
                    if ($v['Field']['required'] == 1) {
                        if ($class) {
                            $class = "{required:true,".$class."}";
                        } else {
                            $class = "{required:true}";
                        }

                    }

                    $title = ($v['Field']['validation'])?$v['Field']['validation']:$v['Field']['field_name'];

                    switch($v['Field']['field_type']){

                        case "select":
                            $options = explode(",", str_replace(", ", ",", $v['Field']['field_value']));
                            $output .= "<select id='".$v['Field']['field_name'].$k."' name='".$v['Field']['field_name']."' class='{$class}' title='Enter valid ".$title."'>";
                            foreach($options as $opt){
                                $output .= "<option value='".$opt."'>".$opt."</option>";
                            }

                            $output .= "</select>";
                            break;

                        default:
                            $output .= "<input type='".$v['Field']['field_type']."' id='".$v['Field']['field_name'].$k."' name='".$v['Field']['field_name']."' title='Enter valid ".$title."' value='".$v['Field']['field_value']."' class='{$class}' />";
                            break;

                    } // switch
                }

                $output .="</td>";
                $output .="</tr>";
            }

            $output .= "<tr>";
            $output .= "<td>&nbsp;</td>";
            $output .= "<td><input type='submit' value='Save'></td>";
            $output .= "</tr>";

            $output .= "</table>";
            $output .= "</form>";
        } else {
            $output = "No form fields available on this offer";
        }

        self::set('output', $output);
        self::set('source', htmlentities($output, ENT_QUOTES));

    }
}
?>